﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using Microsoft.Practices.Unity;
using Microsoft.Practices.Unity.Configuration;

namespace Website.Core
{
    public class UnityContainerFactory
    {
        #region Constants

        private const string UNITY_CONTAINER_KEY = "unity.container";

        #endregion

        #region Private Properties

        /// <summary>
        /// Get or set the Unity container. Instance is hold in current HttpApplication.
        /// </summary>
        /// <value>The container.</value>
        private static IUnityContainer Container
        {
            get
            {
                return (IUnityContainer)HttpContext.Current.Application[UNITY_CONTAINER_KEY];
            }
            set
            {
                HttpContext.Current.Application.Add(UNITY_CONTAINER_KEY, value);
            }
        }

        #endregion

        #region Public Methods

        /// <summary>
        /// Gets the Unity container instance.
        /// </summary>
        /// <returns></returns>
        public static IUnityContainer GetContainer()
        {
            return Container ?? CreateContainer();
        }

        #endregion

        #region Private Methods

        /// <summary>
        /// Creates the Unity container. Settings gets from unity.config file.
        /// </summary>
        /// <returns></returns>
        private static IUnityContainer CreateContainer()
        {
            string configPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "unity.config");

            ExeConfigurationFileMap map = new ExeConfigurationFileMap();
            map.ExeConfigFilename = configPath;
            Configuration config = ConfigurationManager.OpenMappedExeConfiguration(map, ConfigurationUserLevel.None);

            UnityConfigurationSection section = (UnityConfigurationSection)config.GetSection("unity");
            IUnityContainer container = new UnityContainer();

            Container = section.Configure(container, "Default");

            return Container;
        }

        #endregion
    }
}
